package com.itheima.security_service;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {
    @Reference
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //kwlist为一个用户的信息，角色，权限

        User user = userService.findUserByUsername(username);
        if (user!=null){
            List<GrantedAuthority> kwlist = new ArrayList<GrantedAuthority>();
            List<Role> roles = user.getRoles();
            for (Role role : roles) {
                kwlist.add(new SimpleGrantedAuthority(role.getKeyword()));
                List<Permission> permissions = role.getPermissions();
                for (Permission permission : permissions) {
                    kwlist.add(new SimpleGrantedAuthority(permission.getKeyword()));
                }
            }
            return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),kwlist);
        }else {
            return null;
        }
    }
}
